package com.study.hot.jetpack.demo_shopping.viewmodel

import android.content.Context
import android.text.Editable
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.ViewModel
import com.blankj.utilcode.util.ToastUtils
import com.study.hot.jetpack.demo_shopping.MainActivity
import com.study.hot.jetpack.demo_shopping.common.BaseConstant
import com.study.hot.jetpack.demo_shopping.common.listener.SimpleWatcher
import org.jetbrains.anko.startActivity

/**
 * <pre>
 *     author : fauks
 *     time   : 2020/03/26
 *     desc   :
 * </pre>
 */
class LoginModel(name: String, password: String, var context: Context) : ViewModel() {

    //改为LiveData
    val n = ObservableField(name)
    val p = ObservableField(password)
    val repwd = ObservableField("")

    //也可以使用双向绑定无需使用TextWatcher
    val nameWatcher = object : SimpleWatcher() {
        override fun afterTextChanged(s: Editable?) {
            super.afterTextChanged(s)
            n.set(s.toString())
        }
    }

    fun onPasswordChange(s: CharSequence, start: Int, end: Int, count: Int) {
        p.set(s.toString())
    }

    fun login() {
        if (p.get() != repwd.get()) {
            ToastUtils.showShort("两次密码不一致")
            return
        }
        if (n.get() == BaseConstant.USER_NAME && p.get() == BaseConstant.PASSWORD) {
            context.startActivity<MainActivity>()
            (context as AppCompatActivity).finish()
        } else {
            ToastUtils.showShort("登录失败")
        }
    }
}